package com.atguigu.meinian.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.meinian.constant.MessageConstant;
import com.atguigu.meinian.constant.RedisConstant;
import com.atguigu.meinian.mapper.SetmealMapper;
import com.atguigu.meinian.mapper.TravelGroupMapper;
import com.atguigu.meinian.mapper.TravelItemMapper;
import com.atguigu.meinian.pojo.Setmeal;
import com.atguigu.meinian.pojo.TravelGroup;
import com.atguigu.meinian.pojo.TravelItem;
import com.atguigu.meinian.service.SetmealService;
import com.atguigu.meinian.util.MeiNianUtils;
import com.atguigu.meinian.vo.PageResult;
import com.atguigu.meinian.vo.QueryPageBean;
import com.atguigu.meinian.vo.SetmealVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zbystart
 * @create 2021-06-22 9:16
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private TravelGroupMapper travelGroupMapper;

    @Autowired
    private TravelItemMapper travelItemMapper;

    private Logger log = LoggerFactory.getLogger(SetmealServiceImpl.class);


    @Override
    public PageResult query(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.selectByPageAndCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult(),page.getPageNum());
    }

    @Override
    public void removeSetmealById(Integer id) {
        // 检查套餐与跟团游的关联关系
        int count =  setmealMapper.selectTravelGroupCountBySetmealId(id);
        if (count > 0) {
            throw new RuntimeException(MessageConstant.DELETE_SETMEAL_MESSAGE);
        }
        // 获取要删除的套餐的图片
        String image = setmealMapper.selectSetmealImageById(id);
        if (image !=null && image.length() > 0) {
            // 从redis中的套餐图片列表中删除图片
            try {
//                System.out.println("删除的图片：" + image.substring(image.indexOf(com) + com.length() + 1));
                jedisPool.getResource().srem(RedisConstant.SETMEALIMAGENAMES,getALiYunImageName(image));
            } catch (Exception e) {
                log.error("从redis中删除套餐照片失败: " + image);
            }
        }
        setmealMapper.deleteSetmealById(id);

    }

    @Override
    public Setmeal querySetmealById(Integer id) {
        // 查询套餐信息
        Setmeal setmeal = setmealMapper.selectSetmealById(id);
        // 查询套餐关联的跟游团id列表
        List<Integer> travelGroupIds = setmealMapper.selectTravelGroupIdsBySetmealId(id);
        setmeal.setTravelGroupIds(travelGroupIds);
        return setmeal;
    }

    @Override
    public void add(Setmeal setmeal) {
        // 保存套餐信息
        setmealMapper.insert(setmeal);

        // 保存套餐下的跟团游
        setTravelGroupIds(setmeal.getId(),setmeal.getTravelGroupIds());

        // 把套餐的图片名保存到redis中
        String img = setmeal.getImg();
        if (img != null) {
//            System.out.println("套餐保存的图片：" + imageName);
            MeiNianUtils.saveSetmealImageNameToRedis(RedisConstant.SETMEALIMAGENAMES,getALiYunImageName(img),jedisPool);
        }
    }

    @Override
    public void update(SetmealVo setmeal) {
        setmealMapper.updateSetmealById(setmeal);
        setmealMapper.deleteTravelGroupIdsBySetmealId(setmeal.getId());
        setTravelGroupIds(setmeal.getId(),setmeal.getTravelGroupIds());
    }


    private void setTravelGroupIds(Integer setmealId, List<Integer> travelGroupIds) {
        // 保存自游行信息
        if (travelGroupIds != null && travelGroupIds.size() > 0) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("setmealId",setmealId);
            map.put("list", travelGroupIds);
            setmealMapper.insertTravelGroupIds(map);
        }
    }

    private String getALiYunImageName(String image) {
        String com = "com";
        String imageName = image.substring(image.indexOf(com) + com.length() + 1);
//            System.out.println("套餐保存的图片：" + imageName);
        return imageName;
    }

    // 前端页面移动app开发


    @Override
    public List<Setmeal> queryAllSetmeals() {
        Page<Setmeal> setmeals = setmealMapper.selectByPageAndCondition(null);
        return setmeals;
    }

    @Override
    public Setmeal findTravelGroupsBySetmealId(Integer id) {
        // 查询当前套餐信息
        Setmeal setmeal = setmealMapper.selectSetmealById(id);
        // 查询当前套餐下的所有团的id
        List<Integer> travelGroupIds = setmealMapper.selectTravelGroupIdsBySetmealId(id);

        if (travelGroupIds != null && travelGroupIds.size() > 0) {
            // 查询团的信息
            List<TravelGroup> travelGroups = travelGroupMapper.selectTravelGroupsByIds(travelGroupIds);

            // 查询团下的所有自由行
            if (travelGroups != null && travelGroups.size() > 0) {
                for (TravelGroup travelGroup : travelGroups) {
                    // 查询当前团下的所有自由行id
                    List<Integer> travelItemIds = travelGroupMapper.selectTravelItemIds(travelGroup.getId());
                    if (travelItemIds != null && travelItemIds.size() > 0) {
                        // 查询自由行列表
                        List<TravelItem> collect = travelItemIds.stream().map(travelItemId -> {
                            TravelItem travelItem = travelItemMapper.selectTravelitemById(travelItemId);
                            return travelItem;
                        }).collect(Collectors.toList());
                        travelGroup.setTravelItemList(collect);
                    }
                }
            }
            setmeal.setTravelGroups(travelGroups);
        }
        return setmeal;
    }

    @Override
    public Setmeal querySetmealInfoById(Integer id) {
        return setmealMapper.selectSetmealById(id);
    }
}
